package com.gson.oauth;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gson.bean.AuthorizationInfo;
import com.gson.bean.WeixinAccount;
import com.gson.token.Token;
import com.gson.util.HttpKit;
import com.gson.util.JsApiSign;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.Map;

/**
 * @Company 陕西识代运筹信息科技股份有限公司
 * @Discription
 * @Author houfengli
 * @CreateDate 2017/2/20 12:00
 * @Version 1.0
 */
public class Authorize3p{

    private static Logger log =Logger.getLogger(Authorize3p.class);


    /**
     * 微信第三方平台获取api_component_token
     * @param weixinAccount
     * @return
     * @throws Exception
     */
    public static String getComponentToken(WeixinAccount weixinAccount){
        String token = Token.getCache(Token.TokenType.wx3p_access_token, weixinAccount);
        String ticke=Token.getCache(Token.TokenType.wx3p_component_verify_ticket, weixinAccount);
        if(StringUtils.isBlank(token)){
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("component_appid", weixinAccount.getAppId());
            params.put("component_appsecret", weixinAccount.getSecret());
            params.put("component_verify_ticket", ticke);
            String post = JSONObject.toJSONString(params);

            token = HttpKit.post("https://api.weixin.qq.com/cgi-bin/component/api_component_token", post);
            JSONObject object = JSON.parseObject(token);
            token=object.getString("component_access_token");
            Token.cache(Token.TokenType.wx3p_access_token, weixinAccount, token);
        }
        log.info("获取第三方平台component_access_token:"+token);
        return  token;
    }

    /**
     * 获取预授权码pre_auth_code
     * @return
     */
    public static String getPreAuthCode(WeixinAccount weixinAccount) throws Exception{
        String pre_auth_code=Token.getCache(Token.TokenType.wx3p_pre_auth_code, weixinAccount);
        if(StringUtils.isBlank(pre_auth_code)) {
            String commToken=getComponentToken(weixinAccount);
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("component_appid", weixinAccount.getAppId());
            String post = JSONObject.toJSONString(params);

            pre_auth_code = HttpKit.post("https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token="+commToken, post);
            JSONObject object = JSON.parseObject(pre_auth_code);
            pre_auth_code=object.getString("pre_auth_code");
            Token.cache(Token.TokenType.wx3p_pre_auth_code, weixinAccount, pre_auth_code);
        }
        log.info("获取预授权码pre_auth_code:"+pre_auth_code);
        return pre_auth_code;
    }


    /**
     * 使用授权码换取公众号的接口调用凭据和授权信息
     * @param weixinAccount
     * @param authorization_code
     */
    public static AuthorizationInfo queryAuth(WeixinAccount weixinAccount,String authorization_code){
        Assert.notNull(authorization_code);

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("component_appid", weixinAccount.getAppId());
        params.put("authorization_code", authorization_code);
        String post = JSONObject.toJSONString(params);
        String commToken=getComponentToken(weixinAccount);

        String  authorizationInfoStr = HttpKit.post("https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token="+commToken, post);
        JSONObject object = JSON.parseObject(authorizationInfoStr);
        AuthorizationInfo info= object.getObject("authorization_info",AuthorizationInfo.class);
        Token.cache(Token.TokenType.wx3p_authorizer_access_token, info.getAuthorizer_appid(),weixinAccount.getTokenStorager(), info.getAuthorizer_access_token());

        log.info("使用授权码换取公众号的接口调用凭据和授权信息,authorization_code:"+info.toString());
        return  info;
    }

    /**
     *
     * 获取授权公众号 AuthAccessToken
     * @param weixinAccount
     * @return
     */
    public static AuthorizationInfo getAuthAccessToken(WeixinAccount weixinAccount,String appId,String refresh_token){
        Assert.notNull(appId);
        Assert.notNull(refresh_token);
        AuthorizationInfo info;
        String cache = Token.getCache(Token.TokenType.wx3p_authorizer_access_token, appId, weixinAccount.getTokenStorager());
        if(StringUtils.isBlank(cache)){
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("component_appid", weixinAccount.getAppId());
            params.put("authorizer_appid", appId);
            params.put("authorizer_refresh_token", refresh_token);
            String post = JSONObject.toJSONString(params);
            String commToken=getComponentToken(weixinAccount);

            String  authorizationInfoStr = HttpKit.post("https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=" + commToken, post);
            JSONObject object = JSON.parseObject(authorizationInfoStr);
            info = object.toJavaObject(AuthorizationInfo.class);
            Token.cache(Token.TokenType.wx3p_authorizer_access_token, info.getAuthorizer_appid(),weixinAccount.getTokenStorager(),info.getAuthorizer_access_token());
        }else{
            info=new AuthorizationInfo();
            info.setAuthorizer_appid(appId);
            info.setAuthorizer_refresh_token(refresh_token);
            info.setAuthorizer_access_token(cache);
        }
        return  info;
    }

    /**
     * 获取授权方的公众号帐号基本信息
     * @param weixinAccount
     * @param authorizer_appid 授权方appid
     * @return
     */
    public static JSONObject getAuthorizerInfo(WeixinAccount weixinAccount,String authorizer_appid){
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("component_appid", weixinAccount.getAppId());
        params.put("authorizer_appid", authorizer_appid);
        String post = JSONObject.toJSONString(params);
        String commToken=getComponentToken(weixinAccount);

        String  authorizationInfoStr = HttpKit.post("https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token=" + commToken, post);
        log.info("获取授权方的公众号帐号基本信息"+authorizationInfoStr);
        JSONObject object = JSON.parseObject(authorizationInfoStr);
        return object;
    }

    /**
     * JSAPI Sign
     * @param jsapiTicket
     * @param url
     * @return
     */
    public static Map<String,String> getJsApiSign(String jsapiTicket,String url){
        Map<String, String> sign = JsApiSign.sign(jsapiTicket, url);
        return sign;
    }

    public static String getJsapiTicket(WeixinAccount weixinAccount,String appId,String refresh_token) throws Exception {
        AuthorizationInfo authAccessToken = getAuthAccessToken(weixinAccount, appId, refresh_token);
        String jsapiTicket=Token.getCache(Token.TokenType.js_access_token,appId,weixinAccount.getTokenStorager());
        if(StringUtils.isBlank(jsapiTicket)){
            jsapiTicket = JsApiSign.getJsapiTicket(authAccessToken.getAuthorizer_access_token());
            Token.cache(Token.TokenType.js_access_token,appId,weixinAccount.getTokenStorager(),jsapiTicket);
        }
        return jsapiTicket;
    }
}

